{% extends "base.html" %}

{% block title %}编辑课程 - 学生选课系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-edit me-2"></i>编辑课程</h2>
    <div>
        <a href="/courses" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-1"></i>返回课程列表
        </a>
    </div>
</div>

<!-- 编辑课程表单 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">课程信息</h5>
    </div>
    <div class="card-body">
        <form id="editCourseForm">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">课程代码 *</label>
                    <input type="text" class="form-control" name="course_code" id="course_code" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">课程名称 *</label>
                    <input type="text" class="form-control" name="course_name" id="course_name" required>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">学分 *</label>
                    <input type="number" class="form-control" name="credits" id="credits" min="1" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">授课教师</label>
                    <input type="text" class="form-control" name="teacher" id="teacher">
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">容量限制</label>
                    <input type="number" class="form-control" name="capacity" id="capacity" min="0">
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">上课时间</label>
                    <input type="text" class="form-control" name="schedule" id="schedule" placeholder="例如：周一 1-2节">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">上课地点</label>
                    <input type="text" class="form-control" name="location" id="location">
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">课程描述</label>
                <textarea class="form-control" name="description" id="description" rows="3"></textarea>
            </div>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-primary" onclick="updateCourse()">
                    <i class="fas fa-save me-1"></i>保存修改
                </button>
                <button type="button" class="btn btn-outline-secondary" onclick="window.history.back()">
                    <i class="fas fa-times me-1"></i>取消
                </button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
// 获取URL中的课程ID
function getCourseIdFromUrl() {
    const pathParts = window.location.pathname.split('/');
    return pathParts[pathParts.length - 1];
}

// 页面加载时获取课程详情
document.addEventListener('DOMContentLoaded', function() {
    const courseId = getCourseIdFromUrl();
    if (courseId) {
        loadCourseDetail(courseId);
    }
});

// 加载课程详情
async function loadCourseDetail(courseId) {
    try {
        const response = await fetch(`/api/courses/${courseId}`);
        if (!response.ok) {
            throw new Error('获取课程详情失败');
        }
        const course = await response.json();
        populateForm(course);
    } catch (error) {
        console.error('加载课程详情失败:', error);
        alert('加载课程详情失败: ' + error.message);
    }
}

// 填充表单数据
function populateForm(course) {
    document.getElementById('course_code').value = course.course_code || '';
    document.getElementById('course_name').value = course.course_name || '';
    document.getElementById('credits').value = course.credits || '';
    document.getElementById('teacher').value = course.teacher || '';
    document.getElementById('capacity').value = course.capacity || '';
    document.getElementById('schedule').value = course.schedule || '';
    document.getElementById('location').value = course.location || '';
    document.getElementById('description').value = course.description || '';
}

// 更新课程信息
async function updateCourse() {
    const form = document.getElementById('editCourseForm');
    const formData = new FormData(form);
    const courseId = getCourseIdFromUrl();
    
    const courseData = {
        course_code: formData.get('course_code'),
        course_name: formData.get('course_name'),
        credits: parseInt(formData.get('credits')),
        teacher: formData.get('teacher'),
        schedule: formData.get('schedule'),
        location: formData.get('location'),
        capacity: parseInt(formData.get('capacity')) || 0,
        description: formData.get('description')
    };
    
    try {
        const response = await fetch(`/api/courses/${courseId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(courseData)
        });
        
        if (response.ok) {
            alert('课程信息更新成功！');
            window.location.href = `/course-detail/${courseId}`;
        } else {
            const error = await response.json();
            throw new Error(error.error || '更新课程失败');
        }
    } catch (error) {
        console.error('更新课程失败:', error);
        alert('更新课程失败: ' + error.message);
    }
}
</script>
{% endblock %}
